package com.qianfeng.zmt.controller;

import com.qianfeng.http.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {

    @RequestMapping({"/" , "login"})
    public String toLogin(){
        return "login";
    }

    @RequestMapping("login.do")
    public String login(@RequestParam(value = "username" , required = true) String username ,
                        @RequestParam(value = "password" , required = true) String password ,
                        Model model){
        UsernamePasswordToken token = new UsernamePasswordToken(username , password);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            if (subject.isAuthenticated()){
                return "redirect:/index";
            }
        }catch (AuthenticationException e){
        }
        model.addAttribute("error" , ResultCode.LOGIN_ERROR.getDescription());
        return "forward:/";
    }





}
